import React, { useCallback, useEffect } from "react";
import unknown from "@/assets/file-icons/unknown.png";
import PropTypes from "prop-types";

const FILE_URL = process.env.REACT_APP_FILE_URL;

const IMAGE_NAME = ["jpg", "png", "jpeg", "gif", "svg", "bmp", "webp"];
const VIODE_NAME = ["mp4", "avi", "mov", "mkv", "flv", "wmv"];
const AUDIO_NAME = ["mp3", "wav", "ogg", "flac"];
const WORD_NAME = ["doc", "docx"];

const FileIconImg = ({ src, type = "folder", alt = "", ...resProps }) => {
  const [fileSrc, setFileSrc] = React.useState(null);

  const element = useCallback((extension) => {
    return new Promise((resolve) => {
      try {
        const component = require(`@/assets/file-icons/${extension}.png`);
        resolve(component);
      } catch (e) {
        resolve(unknown);
      }
    });
  }, []);

  useEffect(() => {
    if (type === "folder") {
      element("folder").then((res) => setFileSrc(res));
    } else {
      let suffix = type || "default";

      if (WORD_NAME.includes(suffix)) {
        suffix = "word";
      } else if (VIODE_NAME.includes(suffix)) {
        suffix = "video";
      } else if (AUDIO_NAME.includes(suffix)) {
        suffix = "audio";
      }

      if (src && IMAGE_NAME.includes(suffix)) {
        setFileSrc(`${FILE_URL}${src}`);
      } else {
        element(suffix).then((res) => setFileSrc(res));
      }
    }
  }, [element, type, src]);

  return <img style={{ objectFit: "contain", width: "100%" }} {...resProps} src={fileSrc} alt={alt} />;
};

FileIconImg.propTypes = {
  src: PropTypes.string,
  type: PropTypes.string,
  alt: PropTypes.string,
};

export default FileIconImg;
